import serial


class AirQuality:
    def __init__(self, port_name='/dev/ttyUSB0', baud_rate=9600):
        self.ser = serial.Serial(port_name, baud_rate)
        self.data_dict = None

    def calculate_checksum(self, data):
        return sum(data) & 0xFF

    def parse_data(self, data):
        eCO2 = (data[2] << 8) | data[3]
        eCH20 = (data[4] << 8) | data[5]
        TVOC = (data[6] << 8) | data[7]
        PM25 = (data[8] << 8) | data[9]
        PM10 = (data[10] << 8) | data[11]
        temperature = int(data[12]) + (int(data[13]) / 10)
        humidity = int(data[14]) + (int(data[15]) / 10)
        return {
            'eCO2': eCO2,
            'eCH20': eCH20,
            'TVOC': TVOC,
            'PM2.5': PM25,
            'PM10': PM10,
            'temperature': temperature,
            'humidity': humidity
        }

    def read_and_parse_data(self):
        try:
            data = self.ser.read(17)
            if data[0] == 0x3C and data[1] == 0x02:
                checksum = self.calculate_checksum(data[:16])
                if checksum == data[16]:
                    self.data_dict = self.parse_data(data)
                    return True
                else:
                    print("校验和错误")
            else:
                print("帧头错误")
            return False
        except Exception as e:
            print(f"发生错误：{e}")
            return False

    def close(self):
        self.ser.close()


if __name__ == "__main__":
    aq = AirQuality()
    while True:
        if aq.read_and_parse_data():
            print(f"解析后的数据：")
            print(f"eCO2: {aq.data_dict['eCO2']}")
            print(f"eCH20: {aq.data_dict['eCH20']}")
            print(f"TVOC: {aq.data_dict['TVOC']}")
            print(f"PM2.5: {aq.data_dict['PM2.5']}")
            print(f"PM10: {aq.data_dict['PM10']}")
            print(f"Temperature: {aq.data_dict['temperature']}")
            print(f"Humidity: {aq.data_dict['humidity']}")
